<template>
  <div class="reception-caregiver">
    <div class="header">
      <h2>护工状态管理</h2>
      <p>查看护工工作状态，合理分配老人照护任务</p>
    </div>

    <el-card class="main-card">
      <!-- 统计信息 -->
      <div class="stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总护工数" :value="stats.totalCaregivers" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="在岗护工" :value="stats.onDutyCaregivers" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="请假护工" :value="stats.leaveCaregivers" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="空闲护工" :value="stats.availableCaregivers" />
          </el-col>
        </el-row>
      </div>

      <!-- 筛选条件 -->
      <div class="filter">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="护工姓名">
            <el-input
              v-model="filterForm.name"
              placeholder="请输入护工姓名"
              clearable
              @clear="handleFilter"
            />
          </el-form-item>
          <el-form-item label="工作状态">
            <el-select
              v-model="filterForm.status"
              placeholder="请选择状态"
              clearable
              @change="handleFilter"
            >
              <el-option label="在岗" value="在岗" />
              <el-option label="请假" value="请假" />
              <el-option label="休假" value="休假" />
            </el-select>
          </el-form-item>
          <el-form-item label="护工等级">
            <el-select
              v-model="filterForm.level"
              placeholder="请选择等级"
              clearable
              @change="handleFilter"
            >
              <el-option label="一级" value="一级" />
              <el-option label="二级" value="二级" />
              <el-option label="三级" value="三级" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 护工列表 -->
      <div class="caregiver-list">
        <el-table
          :data="caregiverList"
          v-loading="loading"
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="caregiverId" label="护工ID" width="100" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="title" label="职称" width="120" />
          <el-table-column prop="level" label="等级" width="100">
            <template #default="{ row }">
              <el-tag :type="getLevelType(row.level)">
                {{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="工作状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="elderCount" label="负责老人数" width="110">
            <template #default="{ row }">
              <span :class="{ 'full-count': row.elderCount >= 5 }">
                {{ row.elderCount }} / 5
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="elders" label="负责老人" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.elders && row.elders.length > 0">
                <el-tag
                  v-for="elder in row.elders.slice(0, 3)"
                  :key="elder.elderId"
                  size="small"
                  class="elder-tag"
                >
                  {{ elder.name }}
                </el-tag>
                <span v-if="row.elders.length > 3" class="more-text">
                  +{{ row.elders.length - 3 }}位
                </span>
              </div>
              <span v-else class="no-data">暂无负责老人</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click.stop="handleViewDetail(row)"
              >
                查看详情
              </el-button>
              <el-button
                type="success"
                link
                @click.stop="handleAssignElder(row)"
                :disabled="row.elderCount >= 5 || row.status !== '在岗'"
              >
                分配老人
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 护工详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        :title="`护工详情 - ${currentCaregiver.name}`"
        width="700px"
      >
        <div class="caregiver-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="护工ID">
              {{ currentCaregiver.caregiverId }}
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              {{ currentCaregiver.name }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ currentCaregiver.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="职称">
              {{ currentCaregiver.title }}
            </el-descriptions-item>
            <el-descriptions-item label="等级">
              <el-tag :type="getLevelType(currentCaregiver.level)">
                {{ currentCaregiver.level }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="工作状态">
              <el-tag :type="getStatusType(currentCaregiver.status)">
                {{ currentCaregiver.status }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="负责老人数" :span="2">
              {{ currentCaregiver.elderCount }} / 5
            </el-descriptions-item>
          </el-descriptions>

          <!-- 负责老人列表 -->
          <div class="elders-section" v-if="currentCaregiver.elders && currentCaregiver.elders.length > 0">
            <h4>负责老人列表</h4>
            <el-table :data="currentCaregiver.elders" size="small">
              <el-table-column prop="elderId" label="老人ID" width="100" />
              <el-table-column prop="name" label="姓名" width="120" />
              <el-table-column prop="age" label="年龄" width="80" />
              <el-table-column prop="gender" label="性别" width="80" />
              <el-table-column prop="healthStatus" label="健康状况" />
              <el-table-column prop="bedId" label="床位号" width="100" />
            </el-table>
          </div>
          <div v-else class="no-elders">
            <el-empty description="暂无负责老人" :image-size="80" />
          </div>
        </div>
        
        <template #footer>
          <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 分配老人对话框 -->
      <el-dialog
        v-model="assignDialogVisible"
        title="分配老人"
        width="600px"
      >
        <el-form :model="assignForm" label-width="100px">
          <el-form-item label="护工信息">
            <el-input
              :value="`${currentCaregiver.name} (${currentCaregiver.caregiverId})`"
              disabled
            />
          </el-form-item>
          <el-form-item label="选择老人" required>
            <el-select
              v-model="assignForm.elderId"
              placeholder="请选择要分配的老人"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="elder in availableElders"
                :key="elder.elderId"
                :label="`${elder.name} (${elder.elderId}) - ${elder.bedId}床`"
                :value="elder.elderId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分配类型">
            <el-radio-group v-model="assignForm.assignType">
              <el-radio label="长期">长期分配</el-radio>
              <el-radio label="临时">临时分配</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="assignForm.assignType === '临时'" label="临时期限" required>
            <el-date-picker
              v-model="assignForm.tempDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign" :loading="assigning">
            确认分配
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getCaregiverStatus, getAvailableElders, assignElderToCaregiver } from '@/api/reception'

// 响应式数据
const loading = ref(false)
const assigning = ref(false)
const detailDialogVisible = ref(false)
const assignDialogVisible = ref(false)

const caregiverList = ref([])
const currentCaregiver = ref({})
const availableElders = ref([])

const stats = reactive({
  totalCaregivers: 0,
  onDutyCaregivers: 0,
  leaveCaregivers: 0,
  availableCaregivers: 0
})

const filterForm = reactive({
  name: '',
  status: '',
  level: ''
})

const assignForm = reactive({
  elderId: '',
  assignType: '长期',
  tempDateRange: []
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 计算统计信息
const calculateStats = () => {
  const caregivers = caregiverList.value
  stats.totalCaregivers = caregivers.length
  stats.onDutyCaregivers = caregivers.filter(c => c.status === '在岗').length
  stats.leaveCaregivers = caregivers.filter(c => c.status === '请假' || c.status === '休假').length
  stats.availableCaregivers = caregivers.filter(c => 
    c.status === '在岗' && c.elderCount < 5
  ).length
}

// 获取等级类型
const getLevelType = (level) => {
  const levelMap = {
    '一级': 'success',
    '二级': 'warning',
    '三级': 'info'
  }
  return levelMap[level] || 'info'
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '在岗': 'success',
    '请假': 'warning',
    '休假': 'info'
  }
  return statusMap[status] || 'info'
}

// 加载护工列表
const loadCaregivers = async () => {
  loading.value = true
  try {
    const response = await getCaregiverStatus({
      page: pagination.current,
      size: pagination.size,
      ...filterForm
    })
    caregiverList.value = response.data.records || []
    pagination.total = response.data.total || 0
    calculateStats()
  } catch (error) {
    ElMessage.error('加载护工列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理筛选
const handleFilter = () => {
  pagination.current = 1
  loadCaregivers()
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  pagination.current = 1
  loadCaregivers()
}

// 处理行点击
const handleRowClick = (row) => {
  currentCaregiver.value = { ...row }
  detailDialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row) => {
  currentCaregiver.value = { ...row }
  detailDialogVisible.value = true
}

// 分配老人
const handleAssignElder = async (row) => {
  currentCaregiver.value = { ...row }
  assignForm.elderId = ''
  assignForm.assignType = '长期'
  assignForm.tempDateRange = []
  
  try {
    const response = await getAvailableElders()
    availableElders.value = response.data || []
    assignDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载可用老人列表失败：' + error.message)
  }
}

// 提交分配
const submitAssign = async () => {
  if (!assignForm.elderId) {
    ElMessage.warning('请选择要分配的老人')
    return
  }

  if (assignForm.assignType === '临时' && !assignForm.tempDateRange) {
    ElMessage.warning('请选择临时分配的时间范围')
    return
  }

  assigning.value = true
  try {
    await assignElderToCaregiver({
      caregiverId: currentCaregiver.value.caregiverId,
      elderId: assignForm.elderId,
      assignType: assignForm.assignType,
      startDate: assignForm.tempDateRange?.[0],
      endDate: assignForm.tempDateRange?.[1]
    })
    
    ElMessage.success('分配成功')
    assignDialogVisible.value = false
    loadCaregivers()
  } catch (error) {
    ElMessage.error('分配失败：' + error.message)
  } finally {
    assigning.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadCaregivers()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadCaregivers()
}

// 生命周期
onMounted(() => {
  loadCaregivers()
})
</script>

<style scoped>
.reception-caregiver {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 8px 0 0;
  color: #606266;
  font-size: 14px;
}

.main-card {
  min-height: 500px;
}

.stats {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter {
  margin-bottom: 20px;
}

.caregiver-list {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.caregiver-detail {
  padding: 10px 0;
}

.elders-section {
  margin-top: 20px;
}

.elders-section h4 {
  margin-bottom: 10px;
  color: #303133;
}

.no-elders {
  margin-top: 20px;
  text-align: center;
}

.elder-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.more-text {
  color: #909399;
  font-size: 12px;
}

.no-data {
  color: #c0c4cc;
}

.full-count {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
